define(['jquery', 'select2','datetimepicker','mapController',"controller","rights","select2","moment","validate","coordtransform","mapview"], function ($) {

    var c = require("controller");
    var rights = require("rights");
    var mapController = require("mapController");
    var coordtransform = require("coordtransform");
    var moment= require("moment");
    var mapview = require("mapview");

    var tHeight = $(window).height() - 50 - 35;
    $(".content").height(tHeight);

    //获取公司
    var Companys=c.getAllCompanys();
    var nn=[];//公司临时数组
    $.each(Companys,function (i,v) {
        nn.push({id:v.cid,text:v.name})
    });

    return {
        init: function () {
            // test set token
            // localStorage.setItem('token', 'MiMxNDcyNjk0Mjk4QGcuZmx5LWNsb3VkLmNuI1pjZDYzQ2tqeXg1MzdHSkRQWU43SEkxUS9Ecz0=');
            $("#searchCompanys").select2({
                data:nn
            });
            $("#searchState").select2({minimumResultsForSearch:Infinity});
            $('#searchTakeoff,#searchLanding').datetimepicker({
                locale: 'zh-CN',
                format: 'YYYY-MM-DD HH:mm'
            });
            this.searchData={};
            this.initDataTable();
            this.bindEvent();
        },
        dataTable: null,
        delRow:null,
        searchData:{},
        pilots:[],
        models:[],
        initDataTable: function () {
            $("#companys2").select2({
                data:nn
            });
            var self = this;
            this.dataTable = c.myDataTable($("#mmg"), {
                ajax: function (data, callback, settings) {
                    //封装请求参数
                    var param = {
                        page_no: (data.start / data.length),
                        page_size: data.length
                    };
                    $.extend(true,param,self.searchData);
                    //ajax请求数据
                    c.ajax({
                        url: "plan/search",
                        cache: false, //禁用缓存
                        data: param, //传入组装的参数
                        dataType: "json",
                        success: function (result) {
                            //封装返回数据
                            $.each(result.plans,function (i,row) {
                                var space= JSON.parse(row.space);
                                row.sid=space.id;
                                row.sName=space.name;
                                var pilots=row.pilots.split(',');
                                row.pName=[];
                                self.pilots=result.pilots;
                                $.each(result.pilots,function (pi,pilot) { //获取 飞行员名称

                                    if($.inArray(pilot.id,pilots)!=-1){
                                        row.pName.push(pilot.name);
                                    }

                                });
                                row.pName=row.pName.join(',');

                                var fids=row.fids.split(',');
                                row.fName=[];
                                self.models=result.models;
                                $.each(result.models,function (pi,model) {//获取 飞行器 型号

                                    if($.inArray(model.fid,fids)!=-1){
                                        row.fName.push(model.model);
                                    }
                                });




                            });
                            var returnData = {};
                            returnData.draw = data.draw;//这里直接自行返回了draw计数器,应该由后台返回
                            returnData.recordsTotal = result.count;//返回数据全部记录
                            returnData.recordsFiltered = result.count;//后台不实现过滤功能，每次查询均视作全部结果
                            returnData.data = result.plans;//返回的数据列表
                            //console.log(returnData);
                            //调用DataTables提供的callback方法，代表数据已封装完成并传回DataTables进行渲染
                            //此时的数据需确保正确无误，异常判断应在执行此回调前自行处理完毕
                            callback(returnData);
                        }
                    });
                },
                scrollY: (tHeight - 210) + "px",
                scrollX: (1440) + "px",
                scrollCollapse: true,
                "autoWidth": false,
                columns: [
                    {"data": "id", "width": "100px"},
                    {"data": "space","width": "100px"},
                    {"data": "cid","width": "100px"},
                    {"data": "fids","width": "100px"},
                    {"data": "fName","width": "100px"},
                    {"data": "pName","width": "100px"},
                    {"data": "state","width": "100px"},
                    {"data": "takeoff","width": "100px"},
                    {"data": "landing","width": "100px"},
                    {"data": "batch_num","width": "30px"},
                    {"data": "height","width": "30px"}
                ],
                columnDefs: [
                    {
                        "targets": 0,//
                        "data": "id",
                        "render": function (data, type, row) {
                            return moment(row.takeoff,'X').format('YYYYMMDD')+'-'+c.getCompanys(row.cid,'short')+'-'+data;
                        }
                    },
                    {
                        "targets": 1,//
                        "data": "space",
                        "render": function (data, type, row) {
                            space = JSON.parse(row.space);
                            return space.name;

                        }
                    },
                    {
                        "targets": 3,
                        "data": "fids",
                        "render": function (data, type, row) {
                            return data
                        }
                    },
                    {
                        "targets": 2,
                        "data": "cid",
                        "render": function (data, type, row) {
                            return c.getCompanys(row.cid);
                        }
                    },
                    {
                        "targets": 6,//审批状态
                        "data": "state",
                        "render": function (data, type, row) {
                            var val= row.state;
                            if (val == 0) {
                                return '未提交审核';
                            } else if (val == 1) {
                                return '审核中';
                            } else if (val == 2) {
                                return '审核通过';
                            }  else if (val == 3) {
                                return '审核拒绝';
                            } else {
                                return '';
                            }
                        }
                    },
                    {
                        "targets": 7,//起飞时间
                        "data": "takeoff",
                        "render": function (data, type, row) {
                            return c.formatDateWithoutSFromInt(row.takeoff);
                        }
                    },
                    {
                        "targets": 8,//着陆时间
                        "data": "landing",
                        "render": function (data, type, row) {
                            return c.formatDateWithoutSFromInt(row.landing);
                        }
                    },
                    {
                        // 定义操作列,######以下是重点########
                        "targets": 11,
                        "data": 'state',
                        "width": "100px",
                        "render": function (data, type, row) {
                            var html = "<div class='btn-group'>" ;
                            if(data==0){
                                html+= "<a href='#' class='btn btn-sm btn-success audit' data-rights='3008'><i class='fa  fa-hand-pointer-o'></i>提交</a>";
                            }
                            if(data==0||data==3){
                                html+="<a href='#' class='btn btn-sm btn-info edit' data-rights='3004'><i class='fa fa-edit'></i>编辑</a>" +
                                    "<a href='#' class='btn btn-sm btn-danger' data-rights='3005'><i class='fa fa-remove'></i>删除</a>" ;
                            }
                            if(data==2){
                                html+="<a href='#' class='btn btn-sm bg-navy sortie' data-rights='3100'><i class='fa fa-fighter-jet'></i>架次</a>"
                            }
                            html+="<a href='#' class='btn btn-sm btn-vk see' data-toggle='modal' data-target='#myModal'><i class='fa fa-eye'></i>查看</a>" +"</div>";
                            return html;
                        }
                    }],
                drawCallback: function(settings, json) {
                    rights.isShowFn($('.content'));
                }


            });
        },
        bindEvent: function () {
            var self = this;

            $('#add').on('click', function () {
                //添加
                $("#myModal>.modal-dialog").load("plans/form.html", function(){
                    self.formInit()
                });
            });
            $('#mmg').on('click', '.edit', function () {
                //编辑
                var dataRow = self.dataTable.row($(this).parents('tr')).data();

                $("#myModal>.modal-dialog").load("plans/form.html", function () {
                    $("#myModal").modal('show');
                    self.formInit(dataRow, 0)
                });
            }).on('click', '.audit', function () {
                //提交审核
                var dataRow = self.dataTable.row($(this).parents('tr')).data();
                c.ajax({
                        url: "plan/submit",
                        data: {
                            id: dataRow.id,
                            cid:dataRow.cid
                        },
                        success: function (res) {
                            if (res.err == 0) {
                                self.dataTable.ajax.reload();
                            }
                        }
                    }
                )

            }).on('click', '.sortie', function () {
                //架次
                var dataRow = self.dataTable.row($(this).parents('tr')).data();
                $("#sortieModal>.modal-dialog").load("plans/sortie.html", function () {
                    $('#sortieModal').modal('show');
                    self.formPlansInit(dataRow)
                });
            })
                .on('click', '.see', function () {
                    //查看
                    var dataRow = self.dataTable.row($(this).parents('tr')).data();

                    $("#myModal>.modal-dialog").load("plans/view.html", function () {
                        self.viewInit(dataRow)
                    });
                })
                .on('click', '.btn-danger', function () {
                    //删除
                    var dataRow = self.dataTable.row($(this).parents('tr')).data();
                    c.confirm({
                        content: "是否删除",
                        confirm: function () {
                            c.ajax({
                                    url: "plan/delete",
                                    data: {
                                        id: dataRow.id,
                                        cid: dataRow.cid
                                    },
                                    success: function (res) {
                                        if (res.err == 0) {
                                            self.dataTable.ajax.reload();
                                            return
                                        }
                                    }
                                }
                            )
                        }
                    })
                })
                .on('click', 'tr', function () {
                    $(this).siblings().removeClass("select");
                    $(this).toggleClass("select");
                });
      /*      $('#search').on('click',function () {



            });*/

            $('#searchForm').validate({
                rules:{
/*                    searchLanding:{
                        twoDate: ['#searchTakeoff','#searchLanding']
                    },*/
                    searchLanding:{
                        twoDate: ['#searchTakeoff','#searchLanding']
                    }
                },
                submitHandler:function(form){
                    self.searchData={};
                     if($('#searchTakeoff').val()!=""){
                         self.searchData.takeoff=moment($('#searchTakeoff').val()).format('X');
                     }
                    if($('#searchLanding').val()!=""){
                        self.searchData.landing=moment($('#searchLanding').val()).format('X');
                    }
                    if($('#searchCompanys').val()!=""){
                        self.searchData.cid=$('#searchCompanys').val();
                    }
                    if($('#searchState').val()!=""){
                        self.searchData.state=$('#searchState').val();
                    }
                     self.dataTable.draw();
                }
            });


            $('[name="role"]').on('change', function () {
                if ($('[name="role"]').val() === "CORP") {
                    $(".company").removeClass('hide');
                } else {
                    $(".company").addClass('hide');
                }
            });

            $('.search-input').on('keyup', function () {
                console.log(this.value);
                // self.dataTable.search(this.value, false, false).draw();
            })

        },
        formInit:function (dataRow) {
            var self=this;
            var $form = $('.edit-form',$('#myModal'));
            //获取公司
            $("#companys").select2({
                data:nn
            });
            if(dataRow) {//判断是否编辑
                $("#companys").val(dataRow.cid).trigger("change");
            }

            var tempAircrafts =[];//保存当前飞行器数据

            function getOject(cid) {
                c.ajax({
                    url: "suggest/plan",
                    cache: false, //禁用缓存
                    data: {
                        cid:cid
                    }, //传入组装的参数
                    dataType: "json",
                    success: function (result) {
                        if (result.err==0){
                            var tempdata=[];
                            $.each(result.spacelines,function (i,v) {
                                tempdata.push({id:v.id,text:v.name})
                            });
                            $("#sid").empty();
                            $("#sid").select2({//初始化 空域信息
                                data:tempdata
                            });
                            tempdata=[];
                            tempAircrafts=[];
                            $.each(result.aircrafts,function (i,v) {
                                tempdata.push({id:v.fid,text:v.fid});
                            });
                            tempAircrafts=result.aircrafts;
                            $("#fids").empty();
                            $("#fids").select2({//初始化 飞行器
                                tags:true,
                                data:tempdata
                            });

                            tempdata=[];
                            $.each(result.pilots,function (i,v) {
                                tempdata.push({id:v.id,text:v.name})
                            });
                            $("#pilots").empty();
                            $("#pilots").select2({ //初始化 飞行员
                                tags:true,
                                data:tempdata
                            });

                            edit()
                        }

                    }
                });
            }
            $("#companys").on("change", function (e) {
                getOject($("#companys").val());
                $('#fid_type').val('');
            });

            $("#fids").on("change",function (e) {
                var model=[];
                var ss=$(this).val();
                $.each(ss,function (i,v) {
                    $.each(tempAircrafts,function (ii,vv) {
                        if(vv.fid==v){
                            model.push(vv.model);
                            return false;
                        }
                    });
                });
                var model=c.undulpicate(model);
                $('#fid_type').val(model.join(','))
            });
            var edit=setEdit();
            function setEdit() {//设置编辑
                var i=0;
                return function set() {
                    if(dataRow&&i==0){//判断是否编辑
                        $form.find('[name="id"]').val(dataRow.id);
                        $form.find('[name="sid"]').val(dataRow.sid).trigger("change");
                        $form.find('[name="fids"]').val(dataRow.fids.split(',')).trigger("change");
                        $form.find('[name="pilots"]').val(dataRow.pilots.split(',')).trigger("change");
                        $form.find('[name="takeoff"]').val(moment(dataRow.takeoff,'X').format('YYYY-MM-DD HH:mm'));
                        $form.find('[name="landing"]').val(moment(dataRow.landing,'X').format('YYYY-MM-DD HH:mm'));
                        $form.find('[name="batch_num"]').val(dataRow.batch_num);
                        $form.find('[name="height"]').val(dataRow.height);
                        $form.find('[name="remark"]').val(dataRow.remark);
                        $('#myModal').find('.modal-title').text('修改飞行计划');

                        i=1;
                    }

                }
            }

            $('#takeoff,#landing').datetimepicker({
                locale: 'zh-CN',
                format: 'YYYY-MM-DD HH:mm'
            });
            getOject($("#companys").val());

            //地图展示飞行要素
            $('#show_element').on('click',function () {
                $("#mapModal>.modal-dialog").load("element/mapview.html", function(){
                    $("#mapModal").modal("show");

                    c.ajax({
                        url: 'spaceline/detail',
                        dataType: "json",
                        cache: false,
                        data: {
                            cid:$("#companys").val(),
                            id:$("#sid").val()
                        },
                        success: function (res) {
                            if (res.err == 0) {
                                var elements=res.spaceline.elements;
                                elements=typeof elements=="string"?JSON.parse(elements):elements;
                                mapview.init(elements);
                            }
                        }
                    });

                });
            });



            
            //保存验证
                $('.edit-form').validate({
                    rules:{
                        batch_num:{
                            digits:true,
                            min:1
                        },
                        height:{
                            number:true
                        }
                    },
                    messages:{
                        batch_num:{
                            digits:'只能是整数'
                        }
                    },
                    submitHandler:function(form){
                        var mode = $('#myModal').find('.modal-title').text();
                        var formData = $form.serializeArray();
                        var params={};
                        $.each(formData,function (i,v) {
                            params[v.name]=v.value;
                        });
                        params.fids=($("#fids").val()).join(',');
                        params.pilots=($("#pilots").val()).join(',');

                        params.takeoff=moment(params.takeoff).format("X");
                        params.landing=moment(params.landing).format("X");

                        if(params.takeoff>params.landing){
                            c.alert({
                                content:'开始时间必须小于结束时间'
                            });
                            return false
                        }

                        var url='plan/';
                        if (mode === "创建飞行计划") {
                            url+= 'create';
                        } else {
                            url+= 'update';
                        }
                        c.ajax({
                            url: url,
                            dataType: "json",
                            cache: false,
                            data: params,
                            success: function (res) {
                                $('#myModal').modal('hide');
                                if (res.err < 0) {
                                    return;
                                }
                                self.dataTable.ajax.reload();
                            }
                        });



                    }
                });


        },
        viewInit:function (dataRow) {
            var self=this;
            var $form = $('.edit-form',$('#myModal'));

            if(dataRow){//判断是否编辑
                $form.find('[name="id"]').val(dataRow.id);
                $form.find('[name="cid"]').val(c.getCompanys(dataRow.cid));
                $form.find('[name="sid"]').val(dataRow.sName);
                $form.find('[name="fids"]').val(dataRow.fids);
                $form.find('#fid_type').val(dataRow.fName.join(','));

                $form.find('[name="pilots"]').val(dataRow.pName);
                $form.find('[name="takeoff"]').val(moment(dataRow.takeoff,'X').format('YYYY-MM-DD HH:mm'));
                $form.find('[name="landing"]').val(moment(dataRow.landing,'X').format('YYYY-MM-DD HH:mm'));
                $form.find('[name="batch_num"]').val(dataRow.batch_num);
                $form.find('[name="height"]').val(dataRow.height);
                $form.find('[name="remark"]').val(dataRow.remark);

            }


            //地图展示飞行要素
            $('#show_element').on('click',function () {
                $("#mapModal>.modal-dialog").load("element/mapview.html", function(){
                    $("#mapModal").modal("show");

                    c.ajax({
                        url: 'spaceline/detail',
                        dataType: "json",
                        cache: false,
                        data: {
                            cid:dataRow.cid,
                            id:dataRow.sid
                        },
                        success: function (res) {
                            if (res.err == 0) {
                                var elements=res.spaceline.elements;
                                elements=typeof elements=="string"?JSON.parse(elements):elements;
                                mapview.init(elements);
                            }
                        }
                    });

                });
            });
        },

        // 架次
        formPlansInit:function (pdata) {
            var self = this;
            var selectData=[];
            var tempFids=pdata.fids.split(',');
            $.each(tempFids,function (i,v) {
                selectData.push({id:v,text:v});
            });
            $("#fid").select2({
                data:selectData
            });

            selectData=[];
            var tempPilots=pdata.pilots.split(',');
            $.each(self.pilots,function (i,pilot) {
                if($.inArray(pilot.id,tempPilots)!=-1){
                    selectData.push({id:pilot.id,text:pilot.name})
                }

            });
            $("#pilot_id").select2({
                data:selectData
            });

            //列表设置
            var sortieDataTable = c.myDataTable($("#sortie"), {
                ajax: function (data, callback, settings) {
                    //封装请求参数
                    var param = {
                        page_no: (data.start / data.length),
                        page_size: data.length,
                        plan_id:pdata.id
                    };
                    /*$.extend(true, param, searchData);*/
                    //ajax请求数据
                    c.ajax({
                        url: "batch/search",
                        cache: false, //禁用缓存
                        data: param, //传入组装的参数
                        dataType: "json",
                        success: function (result) {
                            //封装返回数据
                            var returnData = {};
                            returnData.draw = data.draw;//这里直接自行返回了draw计数器,应该由后台返回
                            returnData.recordsTotal = result.count;//返回数据全部记录
                            returnData.recordsFiltered = result.count;//后台不实现过滤功能，每次查询均视作全部结果
                            returnData.data = result.batches;//返回的数据列表
                            //console.log(returnData);
                            //调用DataTables提供的callback方法，代表数据已封装完成并传回DataTables进行渲染
                            //此时的数据需确保正确无误，异常判断应在执行此回调前自行处理完毕
                            callback(returnData);
                        }
                    });
                },
                scrollY: (300) + "px",
                scrollCollapse: true,
                columns: [
                    {
                        //所在公司列
                        "data": "cid",
                        "render": function (data, type, row) {
                            return c.getCompanys(row.cid);
                        }
                    },
                    {"data": "fid"},
                    {
                        "data": "pilot_id",
                        "render": function (data, type, row) {
                            var text=[];
                            var temp=data.split(',');
                            $.each(selectData,function (i,pilot) {
                                if($.inArray(pilot.id,temp)!=-1){
                                    text.push(pilot.text)
                                }
                            });
                            return text.join(',');
                        }
                    },
                    {
                        //起飞时间
                        "data": "takeoff",
                        "render": function (data, type, row) {
                            return c.formatDateWithoutSFromInt(row.takeoff);
                        }
                    },
                    {
                        //着陆时间
                        "data": "landing",
                        "render": function (data, type, row) {
                            return c.formatDateWithoutSFromInt(row.landing);
                        }
                    },
                    {
                        // 定义操作列,######以下是重点########
                        "data": null,
                        "render": function (data, type, row) {

                            var html = "<div class='btn-group'>" ;
                            if(!data.takeoff){
                                 html+="<a href='#' class='btn btn-sm btn-primary takeoff' ><i class='fa '></i>起飞</a>";
                             }

                            if(!data.landing!=""&&data.takeoff){
                                html+="<a href='#' class='btn btn-sm btn-primary landing' ><i class='fa '></i>降落</a>";
                            }
                            if(!data.takeoff&&!data.landing){
                                html+= "<a href='#' class='btn btn-sm btn-danger'><i class='fa fa-remove'></i>删除</a>";
                            }

                            html+="</div>";
                                /*                                "<a href='#' class='btn btn-sm btn-info edit' data-toggle='modal' data-target='#sortieModal'><i class='fa fa-edit'></i>编辑</a>" +*/
                            return html;
                        }
                    }
                ]
            });

            $('#addSortie').on('click', function () {
                //添加
                /*$("#sortieFormModal>.modal-dialog").load("plans/sortieForm.html", function(){
                    $("#sortieFormModal").modal('show');
                    self.formSortieInit(id);
                });*/
                var params={
                    cid:pdata.cid,
                    plan_id:pdata.id,
                    fid:$("#fid").val(),
                    pilot_id:$("#pilot_id").val()
                };
                if(!params.fid){
                    c.alert({
                        content:'请选择飞行器'
                    });
                    return false
                }else{
                    params.fid=params.fid;
                }
                if(!params.pilot_id){
                    c.alert({
                        content:'请选择飞行员'
                    });
                    return false
                }else{
                    params.pilot_id=params.pilot_id;
                }
                c.ajax({
                        url: "batch/create",
                        data: params,
                        success: function (res) {
                            if (res.err == 0) {
                                sortieDataTable.draw();
                            }
                        }
                    }
                )


            });

/*            $('#searchSortie').on('click', function () {
                //搜索
                searchData={
                    id:$('#id').val(),
                    pilots:$('#pilots').val()
                };
                sortieDataTable.draw();
            });*/


            $('#sortie').on('click', '.btn-danger',function () {
                    //删除
                var dataRow = sortieDataTable.row( $(this).parents('tr') ).data();
                c.confirm({
                    content:"是否删除",
                    confirm: function(){
                        c.ajax({
                                url: "batch/delete",
                                data: {
                                    cid:pdata.cid,
                                    id:dataRow.id
                                },
                                success: function (res) {
                                    if (res.err == 0) {
                                        sortieDataTable.draw();
                                    }
                                }
                            }
                        )
                    }
                })
             }).on('click', '.takeoff',function () {
                //起飞
                var dataRow = sortieDataTable.row( $(this).parents('tr') ).data();
                c.confirm({
                    content:"是否起飞",
                    confirm: function(){
                        c.ajax({
                                url: "batch/takeoff",
                                data: {
                                    cid:pdata.cid,
                                    id:dataRow.id
                                },
                                success: function (res) {
                                    if (res.err == 0) {
                                        sortieDataTable.draw();
                                    }
                                }
                            }
                        )
                    }
                })
            }).on('click', '.landing',function () {
                //降落
                var dataRow = sortieDataTable.row( $(this).parents('tr') ).data();
                c.confirm({
                    content:"是否降落",
                    confirm: function(){
                        c.ajax({
                                url: "batch/landing",
                                data: {
                                    cid:pdata.cid,
                                    id:dataRow.id
                                },
                                success: function (res) {
                                    if (res.err == 0) {
                                        sortieDataTable.draw();
                                    }
                                }
                            }
                        )
                    }
                })
            });







        }
    }
});



